/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.misc.sap.jco.config;

import com.sap.conn.jco.ext.DestinationDataEventListener;
import com.sap.conn.jco.ext.DestinationDataProvider;
import org.vacoor.nothing.common.util.Resources;

import java.util.Map;
import java.util.Properties;
import java.util.WeakHashMap;

/**
 * 从 classpath 加载配置文件 (晕, 学会 spring 了, 臭长臭长的名字)
 * 默认 JCO 从 user.dir 加载 destinationName.jcoDestination 文件, 这里改为从 classpath
 * <p/>
 * 配置文件中应该包含以下属性
 * 必选:
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_ASHOST}  Host
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_SYSNR}   系统编号
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_CLIENT}  客户端
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_USER}    用户名
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_PASSWD}
 * 可选
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_LANG}
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_POOL_CAPACITY}
 * {@link com.sap.conn.jco.ext.DestinationDataProvider#JCO_PEAK_LIMIT}
 * ...
 *
 * @author vacoor
 */
class ClassPathConfigDestinationDataProvider implements DestinationDataProvider {
    private static final String JCO_DEFAULT_SUFFIX = "jcoDestination";
    private final Object monitor = new Object();
    private Map<String, Properties> configCache = new WeakHashMap<String, Properties>();

    @Override
    public Properties getDestinationProperties(String destinationName) {
        final String destRes = destinationName + "." + JCO_DEFAULT_SUFFIX;
        Properties props = configCache.get(destRes);
        if (props != null) {
            return props;
        }

        synchronized (monitor) {
            if (props == null) {
                props = Resources.getResourceAsProperties(destRes);
                if (props == null) {
                    throw new RuntimeException("File: " + destRes + " does not exist in classpath. ");
                }
                configCache.put(destRes, props);
            }
        }
        return props;
    }

    @Override
    public boolean supportsEvents() {
        return false;
    }

    @Override
    public void setDestinationDataEventListener(DestinationDataEventListener destinationDataEventListener) {
        // unsupported
    }

}
